<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Staff extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('staffModel');
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
    }

    // 角色管理
	public function role() {
        // 学校管理员才可以编辑
        if($this->userType == USER_TYPE_SCHOOL) {
            $showAction = true;
        } else {
            $showAction = false;
        }
        $this->roleDatasource = $this->staffModel->get_role_tree_datasource($this->rmxSchool['id'], $showAction);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "staff". DIRECTORY_SEPARATOR. "role");
	}

    // 获取菜单信息
    public function get_role_info(){
        $roleId = $this->get("id");
        $roleInfo = $this->staffModel->get_role_info($roleId);
        if(!$roleInfo) throw new Exception("角色不存在，修改失败");
        
        // 获取上级菜单名
        $parentRole = $this->staffModel->get_role_info($roleInfo['role_parent_id']);
        $roleInfo['parentName'] = $parentRole['role_name'] ? $parentRole['role_name'] : '顶级角色';

        exit(json("", true, $roleInfo));
    }

    // 获取角色菜单
    public function get_role_menu($roleId){
        $this->load->model('accountModel');

        if($roleId) {
            // 获取角色信息
            $roleInfo = $this->staffModel->get_role_info($roleId);
            $roleData = $this->accountModel->get_admin_menu(USER_TYPE_SCHOOL, $roleInfo['role_menu'], true);
            $roleMenu = $roleData['roleMenu'];
        } else {
            $roleMenu = $this->rmxUser['roleMenu'];
        }
        // 获取权限菜单
        $menuArray = array();
        foreach($roleMenu as $menu) {
            // if($menu['menu_public']) continue;
            
            $tree = array();
            // 菜单属性
            $menuId = $menu['id'];
            $menuIcon = $menu['menu_icon'] ? '<i class="menu-icon fa fa-'. $menu['menu_icon'] .'"></i> ' : '';
            $tree['text'] = $menuIcon. $menu['menu_name'];
            $tree['type'] = 'folder';
            $tree['attr'] = array("id" => $menuId, "pid" => $menu['menu_pid']);
            // 子菜单
            foreach($menu['sub'] as $sub) {

                $subId = $sub['id'];
                $tree['additionalParameters']['children']['label_'. $subId] = array(
                    "text" => $sub['menu_name'],
                    "type" => "item",
                    "attr" => array("id" => $subId, "pid" => $sub['menu_pid'])
                );
            }

            // 如果没有子菜单，就设置为选项
            if(!isset($tree['additionalParameters'])) $tree['type'] = 'item';
            $menuArray["label_". $menuId] = $tree;
        }
        exit(json("", true, $menuArray));
    }

    // 保存角色
    public function role_submit_action(){
        $this->load->model('accountModel');
        $roleId = $this->post("id");
        $roleParentId =$this->post('role_parent_id');
        $roleMenu = $this->post("role_menu");
        $roleName = $this->post("role_name");

        // 检查内容
        if(!$roleName) throw new Exception("角色名不能为空");
        if(!$roleMenu) throw new Exception("角色权限不能为空");

        // 权限菜单去重，重新排序
        $roleMenuArray = explode(",", $roleMenu);
        sort($roleMenuArray);
        $roleMenuArray = array_unique($roleMenuArray);

        // 获取父节点菜单列表
        $parentList = $this->accountModel->get_sub_menu_by_id(0);
        // 使用id作为键值
        $parentList = array_value_to_key($parentList, 'id');
        $roleMenuArrayTemp = $roleMenuArray;
        // var_export($parentList);exit;
        // 过滤掉没有子节点的父节点
        foreach($roleMenuArray as $key => $menuId) {
            if(isset($parentList[$menuId])) {
                // 获取子节点列表
                $subList = $this->accountModel->get_sub_menu_by_id($menuId);
                // 使用id作为键值
                $subList = array_value_to_key($subList, 'id');
                // var_export($subList);exit;
                $temp = false;
                foreach($roleMenuArrayTemp as $value) {
                    if(isset($subList[$value])) {
                        $temp = true;
                        continue;
                    }
                }
                if($temp === false) {
                    // 过滤
                    unset($roleMenuArray[$key]);
                }
            }
            // var_export($roleMenuArray);exit;
        }

        $roleMenu = trim(implode(",", $roleMenuArray), ",");

        // 获取上级角色信息
        $parentRole = $this->staffModel->get_role_info($roleParentId);
        // 生成关系树
        if($parentRole) {
            $treeArray = explode(",", $parentRole['role_parent_tree']);
            $treeArray[] = $roleParentId;
        } else {
            $treeArray = array(0);
        }

        // 入库
        $saveData['school_id'] = $this->rmxUser['school_id'];
        $saveData['role_name'] = $roleName;
        $saveData['role_parent_id'] = $roleParentId;
        $saveData['role_parent_tree'] = implode(",", $treeArray);
        $saveData['role_menu'] = $roleMenu;
        $saveData['updatetime'] = date("Y-m-d H:i:s");
        if($roleId) {
            $roleInfo = $this->staffModel->get_role_info($roleId);
            if($roleInfo['school_id'] != $this->rmxUser['school_id']) throw new Exception("参数错误，删除失败");
            
            $this->db->update(StaffModel::$roleTable, $saveData, "id='{$roleId}'");
        } else {
            $saveData['createtime'] = $saveData['updatetime'];
            $this->db->insert(StaffModel::$roleTable, $saveData);
        }
        // 返回值
        $msg = $roleId ? '修改角色成功' : '添加角色成功';
        exit(json($msg, true));
    }

    // 删除角色
    public function role_delete_action(){
        $roleId = $this->post("id");
        $roleInfo = $this->staffModel->get_role_info($roleId);
        if($roleInfo['school_id'] != $this->rmxUser['school_id']) throw new Exception("参数错误，删除失败");
        // 获取子角色
        $subMenu = $this->staffModel->get_sub_role_by_id($roleId);
        if($subMenu) throw new Exception("当前角色存在子角色，删除失败");
        // 删除菜单
        $save['is_delete'] = 1;
        $save['updatetime'] = date('Y-m-d H:i:s');
        $this->db->update(StaffModel::$roleTable, $save, "id='{$roleId}'");
        exit(json("删除角色成功", true));
    }

    // 执教关系管理页面
	public function coach() {
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取年级对应的行政班级列表
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->gradeNormalClassList = json_encode($classArray);
        // 获取执教角色列表
        $this->coachTypeArr = array(
            array(
                'title' => '班主任',
                'value' => COACH_TYPE_MASTER
            ),
            array(
                'title' => '任课教师',
                'value' => COACH_TYPE_TEACHER
            ),
            array(
                'title' => '年级管理员',
                'value' => COACH_TYPE_GRADE_ADMIN
            ),
            array(
                'title' => '学校管理员',
                'value' => COACH_TYPE_SCHOOL_ADMIN
            )
        );
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "staff". DIRECTORY_SEPARATOR. "coach");
    }
    // 获取执教关系列表
    public function get_coach_list() {
        $this->load->model('classesModel');
        // 教师名称
        if($this->get('realname')) {
            $totalParams['teacherRealname'] = $data['teacherRealname'] = $this->get('realname');
        }
        // 班级筛选
        if($this->get('class_id')) {
            $totalParams['classId'] = $data['classId'] = $this->get('class_id');
        }
        // 学生年级筛选
        if(empty($this->get("class_id")) && $this->get("grade_id")) {
            $params['gradeId'] = $this->get("grade_id");
            $params['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($params);
            $totalParams['classSet'] = $data['classSet'] = array_value_implode($classList, "id");
        }
        // 权限角色
        if($this->get('coach_type')) {
            $totalParams['coachType'] = $data['coachType'] = $this->get('coach_type');
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campus_id'] = $this->campusInfo['id'];
        $total = $this->staffModel->get_coach_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campus_id'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $coachList = $this->staffModel->get_coach_list($data);
        if($coachList) {
            // 获取本校全部班级
            $classParams['schoolId'] = $this->rmxSchool['id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            $classParams['isDelete'] = 0;
            $classList = $this->classesModel->get_class_list($classParams);
            $classList = array_value_to_key($classList, 'id');
            // 获取学校所有科目
            $lesParams['schoolId'] = $this->rmxSchool['id'];
            $lesParams['isDelete'] = 0;
            $subjectList = $this->schoolModel->get_lesson_list($lesParams);
            $subjectList = array_value_to_key($subjectList, 'id');
            foreach($coachList as &$coach) {
                // 获取班级名称
                $classIdArr = explode(',', $coach['class_ids']);
                $classnameArr = array();
                foreach($classIdArr as $classId) {
                    if(isset($classList[$classId])) {
                        array_push($classnameArr, $classList[$classId]['class_name']);
                    }
                }
                $coach['class_name'] = implode('，', $classnameArr);

               // 获取科目名称
               if($coach['subject_ids']) {
                    $subjectIdArr = explode(',', $coach['subject_ids']);
                    $subjectNameArr = array();
                    foreach($subjectIdArr as $subjectId) {
                        if(isset($subjectList[$subjectId])) {
                            array_push($subjectNameArr, $subjectList[$subjectId]['lesson_name']);
                        }
                    }
                    $coach['subject_name'] = implode('，', $subjectNameArr);
               } else {
                   $coach['subject_name'] = '';
               }
               $gradeName = '';
               // 获取执教角色名称
               if($coach['coach_type'] == COACH_TYPE_MASTER) {
                    $coach['coach_type_chinese'] = '<span class="label-primary" style="color:#fff;font-size:0.3rem;padding: 2px 5px;">班主任</span>';
               } elseif($coach['coach_type'] == COACH_TYPE_TEACHER) {
                    $coach['coach_type_chinese'] = '<span class="label-success" style="color:#fff;font-size:0.3rem;padding: 2px 5px;">任课教师</span>';
               } elseif($coach['coach_type'] == COACH_TYPE_GRADE_ADMIN) {
                    $coach['coach_type_chinese'] = '<span class="label-warning" style="color:#fff;font-size:0.3rem;padding: 2px 5px;">年级管理员</span>';
                    // 获取年级名称
                    if($coach['grade_id']) {
                        $gradeInfo = $this->classesModel->get_grade_info($coach['grade_id']);
                        $gradeName = $gradeInfo ? $gradeInfo['grade_name'] : '';
                    }
               } elseif($coach['coach_type'] == COACH_TYPE_SCHOOL_ADMIN) {
                    $coach['coach_type_chinese'] = '<span class="label-danger" style="color:#fff;font-size:0.3rem;padding: 2px 5px;">学校管理员</span>';
                } 
               $coach['grade_name'] = $gradeName;
            }
        }
        // 返回值
        exit(admin_table_data($total, $coachList));   
    }

    // 执教关系编辑页面
	public function coach_edit($id=0) {
        if($id) {
            $coachInfo = $this->staffModel->get_coach_info($id);
            // 获取教师名称
            $teacherInfo = $this->schoolModel->get_teacher_info($coachInfo['teacher_id']);
            $coachInfo['teacher_realname'] = $teacherInfo['realname'];
            // 获取班级名称
            // $classInfo = $this->classesModel->get_class_info($coachInfo['class_id']);
            // $coachInfo['class_name'] = $classInfo['class_name'];

            // 获取班级列表
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $this->rmxUser['school_id'];
            $classParams['campusId'] = $this->campusInfo['id'];
            $classList = $this->classesModel->get_class_list($classParams);
            $classIdArr = explode(',', $coachInfo['class_ids']);
            // 过滤掉已删除
            $newClassIdArr = array();
            // 使用id作为键
            $classList = array_value_to_key($classList, 'id');
            $classnameArr = array();
            foreach($classIdArr as $classId) {
                if(isset($classList[$classId])) {
                    array_push($classnameArr, $classList[$classId]['class_name']);
                    array_push($newClassIdArr, $classId);
                }
            }
            $coachInfo['class_name'] = implode('，', $classnameArr);
            $coachInfo['class_ids'] = implode(',', $newClassIdArr);
            // 获取执教科目id数组
            if($coachInfo['subject_ids']) {
                $coachInfo['subjectIdArr'] = explode(',', $coachInfo['subject_ids']);
            } else {
                $coachInfo['subjectIdArr'] = array();
            }

            $this->coachInfo = $coachInfo;
        }

        // 获取执教角色列表
        $this->coachTypeArr = array(
            array(
                'title' => '班主任',
                'value' => COACH_TYPE_MASTER
            ),
            array(
                'title' => '任课教师',
                'value' => COACH_TYPE_TEACHER
            ),
            array(
                'title' => '年级管理员',
                'value' => COACH_TYPE_GRADE_ADMIN
            ),
            array(
                'title' => '学校管理员',
                'value' => COACH_TYPE_SCHOOL_ADMIN
            )
        );
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $this->subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 获取学校所有年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeArr = $this->classesModel->get_grade_list($gradeParams);
                // exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "staff". DIRECTORY_SEPARATOR. "coach_edit");
    }
    // 保存执教关系
    public function save_coach_action() {
        $coachId = $this->post('id');
        $teacherId = $this->post('teacher_id');
        $classIds = $this->post('class_ids');
        $coachType = $this->post('coach_type');
        $subjectIds = $this->post('subject_ids') ? $this->post('subject_ids') : '';
        $gradeId = $this->post('grade_id') ? $this->post('grade_id') : 0;
        // var_export($subjectIds);exit;
        if(empty($teacherId)) {
            throw new Exception('教师不能为空');
        }

        $classIdArr = explode(',', $classIds);
        if($coachType == COACH_TYPE_MASTER) {
            if(empty($classIds)) {
                throw new Exception('班级不能为空');
            }
            $subjectIds = '';
            $gradeId = 0;
            foreach($classIdArr as $classId) {
                // 判断该班级是否已设置班主任
                $coachParams['schoolId'] = $this->rmxSchool['id'];
                $coachParams['campusId'] = $this->campusInfo['id'];
                $coachParams['classId'] = $classId;
                $coachParams['coachType'] = COACH_TYPE_MASTER;
                $coachParams['teacherId'] = $teacherId;
                $coachInfo = $this->staffModel->get_coach_list($coachParams);
                if($coachInfo) {
                    if(empty($coachId)) {
                        // 插入操作
                        throw new Exception('班主任不能重复设置');
                    }
                }
            }
        } elseif($coachType == COACH_TYPE_TEACHER) {
            if(empty($classIds)) {
                throw new Exception('班级不能为空');
            }
            if(empty($subjectIds)) {
                throw new Exception('执教科目不能为空');
            }
            $gradeId = 0;
            foreach($classIdArr as $classId) {
                // 判断该任课关系是否已存在
                $coachParams['schoolId'] = $this->rmxSchool['id'];
                $coachParams['campusId'] = $this->campusInfo['id'];
                $coachParams['classId'] = $classId;
                $coachParams['coachType'] = COACH_TYPE_TEACHER;
                $coachParams['teacherId'] = $teacherId;
                $coachParams['subjectIdSet'] = $subjectIds;
                $coachInfo = $this->staffModel->get_coach_list($coachParams);
                if($coachInfo) {
                    if(empty($coachId)) {
                        // 插入操作
                        throw new Exception('任课教师不能重复设置');
                    } else {
                        // 更新操作
                        if($coachInfo[0]['id'] != $coachId) {
                            throw new Exception('任课教师不能重复设置');
                        } 
                    }
                }
            }
        } elseif($coachType == COACH_TYPE_GRADE_ADMIN) {
            if(empty($gradeId)) {
                throw new Exception('年级不能为空');
            }
            $subjectIds = '';
            $classIds = '';
            // 判断该记录是否已存在
            $coachParams['schoolId'] = $this->rmxSchool['id'];
            $coachParams['campusId'] = $this->campusInfo['id'];
            $coachParams['gradeId'] = $gradeId;
            $coachParams['teacherId'] = $teacherId;
            $coachParams['coachType'] = COACH_TYPE_GRADE_ADMIN;
            $coachInfo = $this->staffModel->get_coach_list($coachParams);
            if($coachInfo) {
                if(empty($coachId)) {
                    // 插入操作
                    throw new Exception('不能重复设置');
                }
            }
        }
        if(empty($coachId)) {
            // 添加操作
            $this->db->insert(StaffModel::$coachTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'teacher_id' => $teacherId,
                'class_ids' => $classIds,
                'coach_type' => $coachType,
                'subject_ids' => $subjectIds,
                'grade_id' => $gradeId,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 修改操作;
            $this->db->update(StaffModel::$coachTable, array(
                'teacher_id' => $teacherId,
                'class_ids' => $classIds,
                'coach_type' => $coachType,
                'subject_ids' => $subjectIds,
                'grade_id' => $gradeId,
                'updatetime' => date('Y-m-d H:i:s')
            ), "id = {$coachId}");
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 删除执教关系
    public function delete_coach_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(StaffModel::$coachTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 导出执教老师模板
    public function export_teacher_coach() {
        // // 获取数据
        // $data['schoolId'] = $this->rmxSchool['id'];
        // $data['campusId'] = $this->campusInfo['id'];
        // $data['orderByClassName'] = 1;
        // $brandList = $this->classesModel->get_brand_list_left_join_class($data);
        // $exportData = array();
        // echo '<pre>';var_export($studentList);exit;
        $firstRow = array(
            '执教班级',
            '教师名称',
            '执教科目'
        );
        $exportData[] = $firstRow;
        $widthParams = array(
            array(
                'index' => 'A',
                'width' => 20
            ),
            array(
                'index' => 'B',
                'width' => 25
            ),
            array(
                'index' => 'C',
                'width' => 25
            )
        );
        exportExcel('执教老师数据模板', $exportData, $widthParams);
    }
    // 导出班主任模板
    public function export_master_coach() {
        $firstRow = array(
            '班主任班级',
            '教师名称',
        );
        $exportData[] = $firstRow;
        $widthParams = array(
            array(
                'index' => 'A',
                'width' => 20
            ),
            array(
                'index' => 'B',
                'width' => 25
            ),
        );
        exportExcel('班主任数据模板', $exportData, $widthParams);
    }
}